// import crypto from 'crypto'
import { SHA256, enc } from 'crypto-js';

export default function signatureJsonObj(secretKey, paramsJson) {
    var sorter = function (paramsJson) {
        var sortedJson = {};
        var sortedKeys = Object.keys(paramsJson).sort();
        for (var i = 0; i < sortedKeys.length; i++) {
            sortedJson[sortedKeys[i]] = paramsJson[sortedKeys[i]]
        }
        return sortedJson;
    }
    var sortedParam = sorter(paramsJson);

    console.log(sortedParam);

    var needSignatureStr = "";
    for (var key in sortedParam) {
        var value = sortedParam[key];
        needSignatureStr = needSignatureStr + key + value;
    }
    needSignatureStr += secretKey;

    console.log(needSignatureStr);

    return SHA256(needSignatureStr).toString(enc.Hex);
};

export function getTimestamp() {
    return Math.floor(Date.now() / 1000);
}

export function filterQueryTimestamp(request, env) {
    var authToken = request.headers.get('Token')
    if (!authToken) {
        return Response.json({ msg: `not found Token header` });
    }

    var searchParams = new URLSearchParams(new URL(request.url).search.split('?')[1])
    var t = searchParams.get('t')

    if (t == null) {
        return Response.json({ msg: `not found parameter t` });
    }

    var serverTime = getTimestamp();

    if (Math.abs(t - serverTime) > 300) {
        return Response.json({ msg: `time mismatch server time is ${serverTime}` });
    }

    var sign = signatureJsonObj(env.FilterSecret, { Time: t });

    console.log(sign);

    if (authToken != sign) {
        return Response.json({ msg: `sign check not match` });
    }
}